<template>
  <div class="app-container" style="height: 100%">
    <div
      class="app-container-inner"
      style="display: flex; flex-direction: column"
      v-loading="loading"
      element-loading-text="加载中..."
    >
      <div class="header">
        <div style="display: flex; gap: 5px">
          <HPlainButton @click="createDialog = true">创建编码</HPlainButton>
          <HPlainButton @click="onImportCode">导入编码</HPlainButton>
          <HPlainButton @click="onExportCode">导出编码</HPlainButton>
          <el-dropdown trigger="click">
            <HButton :disabled="activeId.length == 0">
              批量操作
              <el-icon class="el-icon--right">
                <arrow-down />
              </el-icon>
            </HButton>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleClick(1)">
                  <el-icon>
                    <CircleCheck />
                  </el-icon>
                  批量激活
                </el-dropdown-item>
                <el-dropdown-item @click="handleClick(2)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                  批量删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <!-- 搜索条件 -->
        <div class="search">
          <!-- 日期范围 -->
          <DateRange
            start-date-picker-width="120px"
            end-date-picker-width="120px"
            ref="dateRangeRef"
            @change="handleDateChange"
          />

          <!-- 商品类型 -->
          <el-select
            v-model="type"
            style="width: 100px"
            placeholder="商品类型"
            @change="getList(true)"
            filterable
            clearable
          >
            <el-option :value="1" label="成品" />
            <el-option :value="2" label="配件" />
          </el-select>

          <!-- 商品品牌 -->
          <el-select
            v-model="brandId"
            :filter-method="remoteMethod"
            :loading="loading2"
            remote-show-suffix
            placeholder="商品品牌"
            @change="getList(true)"
            filterable
            clearable
            style="width: 100px"
          >
            <el-option
              v-for="(item, index) in brandData"
              :key="index"
              :value="item.id"
              :label="item.name"
            />
          </el-select>

          <!-- 商品分类 -->
          <el-select
            v-model="typeId"
            placeholder="商品分类"
            :filter-method="remoteMethod2"
            :loading="loading3"
            @change="getList(true)"
            filterable
            clearable
            remote-show-suffix
            style="width: 100px"
          >
            <el-option
              v-for="(item, index) in typeData"
              :key="index"
              :value="item.id"
              :label="item.name"
            />
          </el-select>

          <!-- 商品型号/商品名称 -->
          <el-input
            v-model="goods"
            @keyup.enter="codeKeyup"
            clearable
            placeholder="商品型号/商品名称"
            style="width: 140px"
          />

          <!-- 防伪编码 -->
          <el-input
            v-model="code"
            @keyup.enter="codeKeyup"
            @clear="getList(true)"
            style="width: 180px"
            clearable
            placeholder="防伪编码"
          />

          <HButton type="primary" @click="getList(true)">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </HButton>
          <HButton @click="clearVlaue">
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </HButton>
        </div>
      </div>
      <div class="table">
        <el-table
          border
          stripe
          resizable
          :data="codeList"
          style="width: 100%; position: absolute"
          height="100%"
          @cell-dblclick="goDetail"
          @selection-change="changeAll"
        >
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
          <el-table-column type="selection" width="40" fixed />

          <!-- 序号 -->
          <el-table-column width="50" show-overflow-tooltip label="序号" fixed>
            <template v-slot="scope">
              <span style="padding: 0 !important">{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>

          <!-- 一物一码 -->
          <el-table-column
            show-overflow-tooltip
            prop="securityCode"
            fixed
            label="一物一码"
            width="140"
          >
            <template v-slot="scope">
              <HLink @click="goDetail(scope.row)">
                {{ scope.row.securityCode }}
              </HLink>
            </template>
          </el-table-column>

          <!-- 批次号 -->
          <el-table-column show-overflow-tooltip prop="batchCode" label="批次号" width="150" />

          <!-- 编码类型 -->
          <el-table-column show-overflow-tooltip prop="type" label="编码类型" width="74">
            <template v-slot="scope">
              <span v-if="scope.row.type == 1">成品</span>
              <span v-else>配件</span>
            </template>
          </el-table-column>

          <!-- 商品信息 -->
          <el-table-column
            show-overflow-tooltip
            prop="brand goodsSpecName goodsName goodsModel"
            label="商品信息"
            width="300"
          >
            <template v-slot="scope">
              <div style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis">
                {{ scope.row.brand }} &nbsp; {{ scope.row.goodsModel }} &nbsp;
                {{ scope.row.goodsName }} &nbsp;
                {{ scope.row.goodsSpecName }}
              </div>
            </template>
          </el-table-column>

          <!-- 是否激活 -->
          <el-table-column show-overflow-tooltip prop="activa" label="是否激活" width="84">
            <template v-slot="scope">
              <HStatus type="success" v-if="scope.row.activa">已激活</HStatus>
              <HStatus type="info" v-else>未激活</HStatus>
            </template>
          </el-table-column>

          <!-- 客户信息 -->
          <el-table-column show-overflow-tooltip label="客户信息" width="200">
            <template #default="scope">
              {{ scope.row.username }}&nbsp;{{ scope.row.phone }}
            </template>
          </el-table-column>

          <!-- 编码状态 -->
          <el-table-column prop="status" label="编码状态" width="84">
            <template #default="scope">
              <HStatus type="info" v-if="scope.row.status === 3">已过保</HStatus>
              <HStatus v-if="scope.row.status === 2">质保中</HStatus>
              <HStatus type="info" v-if="scope.row.status === 1">未质保</HStatus>
              <HStatus type="error" v-if="scope.row.status === 4">已作废</HStatus>
            </template>
          </el-table-column>

          <!-- 仓储编码 -->
          <el-table-column show-overflow-tooltip prop="storeCode" label="仓储编码" width="150" />

          <!-- 编码出入库状态 -->
          <el-table-column prop="status" label="编码出入库状态" width="110">
            <template #default="scope">
              <HStatus type="info" v-if="scope.row.storeStatus === 1">未出入库</HStatus>
              <HStatus type="warning" v-if="scope.row.storeStatus === 2">预入库</HStatus>
              <HStatus type="success" v-if="scope.row.storeStatus === 3">已入库</HStatus>
              <HStatus type="warning" v-if="scope.row.storeStatus === 4">预出库</HStatus>
              <HStatus type="success" v-if="scope.row.storeStatus === 5">已出库</HStatus>
            </template>
          </el-table-column>

          <!-- 编码来源 -->
          <el-table-column prop="codeSource" label="编码来源" width="118">
            <template #default="scope">
              <span v-if="scope.row.codeSource == 1">系统创建</span>
              <span v-if="scope.row.codeSource == 2">系统导入</span>
              <span v-if="scope.row.codeSource == 3">工单报单创建</span>
              <span v-if="scope.row.codeSource == 4">第三方系统编码</span>
            </template>
          </el-table-column>

          <!-- 出库网点 -->
          <el-table-column show-overflow-tooltip prop="network" label="出库网点" width="200" />

          <!-- 创建时间 -->
          <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="128" />

          <!-- 更新时间 -->
          <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="128" />
        </el-table>
      </div>
      <div class="footer">
        <Pagination
          ref="paginDom"
          :list_total="total"
          @size-change="getSizeList"
          @current-change="getNumList"
        />
      </div>

      <!-- 创建编码弹窗 -->
      <HModal v-model="createDialog" title="创建编码" :width="750">
        <CreateCodepopup @close-popup="createDialog = $event" @update-list="getList" />
      </HModal>

      <!-- 导出编码弹窗-->
      <HModal
        v-model="exportCodeModalState"
        title="导出编码"
        @close="exportCodeModalState = false"
        size="small"
      >
        <div class="export_code_modal_form_content">
          <!-- 日期范围 -->
          <div class="date_range">
            <div class="start-date">
              <el-date-picker
                v-model="startDate"
                type="date"
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </div>
            <span style="line-height: 28px">~</span>
            <div class="end-date">
              <el-date-picker
                v-model="endDate"
                type="date"
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </div>
          </div>

          <div class="form_item_container">
            <el-select v-model="type" placeholder="商品类型" @change="getList" filterable clearable>
              <el-option :value="1" label="成品" />
              <el-option :value="2" label="配件" />
            </el-select>

            <el-select
              v-model="brandId"
              :filter-method="remoteMethod"
              :loading="loading2"
              remote-show-suffix
              placeholder="商品品牌"
              @change="getList"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in brandData"
                :key="index"
                :value="item.id"
                :label="item.name"
              />
            </el-select>
          </div>

          <div class="form_item_container">
            <el-select
              v-model="typeId"
              placeholder="商品分类"
              :filter-method="remoteMethod2"
              :loading="loading3"
              @change="getList"
              filterable
              clearable
              remote-show-suffix
            >
              <el-option
                v-for="(item, index) in typeData"
                :key="index"
                :value="item.id"
                :label="item.name"
              />
            </el-select>

            <el-input
              v-model="goods"
              @keyup.enter="codeKeyup"
              clearable
              placeholder="商品型号/商品名称"
            />
          </div>

          <div class="form_item_container">
            <el-input v-model="code" @keyup.enter="codeKeyup" clearable placeholder="防伪编码" />

            <div class="filter">
              <HButton type="primary" @click="getList">
                <el-icon>
                  <Search />
                </el-icon>
                搜索
              </HButton>
              <HButton @click="clearVlaue">
                <el-icon>
                  <RefreshRight />
                </el-icon>
                重置
              </HButton>
            </div>
          </div>
        </div>

        <template #footerRight>
          <HButton is-modal type="primary" @click="onConfirmExport" :loading="exportLoading"
            >导出</HButton
          >
          <HButton is-modal @click="onCancelExport">取消</HButton>
        </template>
      </HModal>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, onMounted, reactive, onBeforeUnmount, watch } from 'vue'
  import { Search, RefreshRight, CircleCheck, ArrowDown, Delete } from '@element-plus/icons-vue'
  import { useRouter, useRoute } from 'vue-router'
  import { getCodeList, activCode, deleteCode, codeExportExcel } from '@/api/code'
  import { brandPageSelect, typePageSelect } from '@/api/goodsInfo'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import CreateCodepopup from '../../code/list/detail/components/createCodepopup/index.vue'
  import moment from 'moment'
  import DateRange from '@/components/DateRange.vue'
  import _ from 'lodash'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.snCode.codeList,
  })

  const route = useRoute()
  const router = useRouter()
  const type = ref(null) //商品类型  类型：1-成品，2-配件
  const code = ref(null)

  // 开始日期
  const startDate = ref('')

  // 结束日期
  const endDate = ref('')

  // 日期范围选择器组件
  const dateRangeRef = ref<InstanceType<typeof DateRange> | null>(null)

  const createDialog = ref(false)
  const loading = ref(true)
  const loading2 = ref(false)
  const loading3 = ref(false)
  const total = ref(0)
  const brandId = ref('') //品牌ID
  const brandData = ref(null)
  const typeId = ref('') //商品分类ID
  const typeData = ref(null)
  const codeList = ref(null)
  const goods = ref('')
  const exportCodeModalState = ref(false)
  const dataPage = reactive({
    limit: 0,
    name: '',
    page: 0,
  })
  const dataPage2 = reactive({
    limit: 0,
    name: '',
    page: 0,
  })
  const exportLoading = ref(false)

  const onImportCode = () => {
    router.push({ path: '/code/codeExcelImport' })
  }
  // 查看详细
  const goDetail = (row) => {
    router.push({ path: `/code/codetail/${row.id}/${row.tableType}` })
  }
  const paginDom = ref() // 分页dom

  const clearVlaue = () => {
    isStartDateGreaterThanEndDate.value = false
    if (dateRangeRef.value) {
      dateRangeRef.value.resetDateRange()
    }

    // 初始化
    code.value = null
    type.value = null
    startDate.value = ''
    endDate.value = ''
    goods.value = ''
    brandId.value = ''
    typeId.value = null
    getList()
  }
  const activeId = ref([])
  const codeKeyup = () => {
    if (code.value || goods.value) {
      getList(true)
    } else {
      ElMessage({
        showClose: true,
        message: '请输入关键词搜索',
        duration: 4000,
        type: 'warning',
      })
    }
  }
  onMounted(() => {
    getList(false)
    brandPageSelect(dataPage).then((res) => {
      brandData.value = res.data.data.rows
    })
    typePageSelect(dataPage2).then((res) => {
      typeData.value = res.data.data.rows
    })
    handleWindowResize()
    window.addEventListener('resize', handleWindowResize)
  })
  const handleWindowResize = () => {
    // windowHeight.value = window.innerHeight - window.innerHeight * 0.33
  }
  onBeforeUnmount(() => {
    window.removeEventListener('resize', handleWindowResize)
  })

  // 开始日期是否大于结束日期
  const isStartDateGreaterThanEndDate = ref(false)

  // 日期更新事件
  const handleDateChange = (param: {
    startDate: string
    endDate: string
    isStartDateGreaterThanEndDate: boolean
  }) => {
    startDate.value = param.startDate
    endDate.value = param.endDate
    isStartDateGreaterThanEndDate.value = param.isStartDateGreaterThanEndDate
    if (param.isStartDateGreaterThanEndDate) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
      })
    }
  }

  // 获取列表数据
  const getList = async (val = false) => {
    if (isStartDateGreaterThanEndDate.value) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
      })
      return
    }

    loading.value = true
    const data = {
      code: code.value, //防伪编码
      endTime: endDate.value ? endDate.value : '', //编码创建结束时间
      limit: paginDom.value.size, //每页显示数量
      page: paginDom.value.current, //当面页码
      startTime: startDate.value ? startDate.value : '', //编码创建开始时间
      type: type.value, //类型：1-成品，2-配件
      goods: goods.value, //商品关键词：商品型号/商品名称
      brandId: brandId.value, //品牌ID
      typeId: typeId.value, //商品分类ID
    }
    const res = await getCodeList(data)
    loading.value = false
    if (res.data.code == 20000) {
      codeList.value = res.data.data.rows
      total.value = parseInt(res.data.data.total) || 0
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
        })
    }
  }
  // 导出编码
  const onExportCode = () => {
    exportCodeModalState.value = true
  }
  // 取消导出
  const onCancelExport = () => {
    exportCodeModalState.value = false
  }
  // 确认导出
  const onConfirmExport = () => {
    exportLoading.value = true
    const data = {
      brandId: brandId.value, //品牌ID
      code: code.value, //防伪编码
      endTime: endDate.value ? endDate.value : '', //编码创建结束时间
      goods: goods.value, //商品关键词：商品型号/商品名称
      limit: paginDom.value.size, //每页显示数量
      page: paginDom.value.current, //当面页码
      startTime: startDate.value ? startDate.value : '', //编码创建开始时间
      type: type.value, //类型：1-成品，2-配件
      typeId: typeId.value, //商品分类ID
    }
    codeExportExcel(data).then((res) => {
      // 因为前端把responseType: 'blob'放到请求头里，所以当后端响应JSON时也会把JSON转为blob
      // 所以需要将响应的数据转回JSON对象，如果转换成功就说明返回的是JSON，否则则是文件流
      let reader = new FileReader()
      reader.readAsText(res.data)
      reader.onload = function (result) {
        try {
          // 解析对象成功，说明后端返回的是JSON
          let resData = JSON.parse(result.target.result as string)
          ElMessage({
            showClose: true,
            message: resData.message,
            type: resData.code === 61000 ? 'warning' : 'error',
            offset: 200,
          })
        } catch (err) {
          // 解析失败，说明后端返回的是文件流
          ElMessage({
            showClose: true,
            message: '服务商数据导出成功',
            type: 'success',
            offset: 200,
          })
          const url = window.URL.createObjectURL(new Blob([res.data], { type: '.xlsx' }))
          const link = document.createElement('a')
          link.href = url
          link.download = `编码档案_${moment(new Date()).format('YYYYMMDD')}.xlsx`
          link.click()
        }
      }
      exportLoading.value = false
    })
  }

  const remoteMethod = _.throttle((val) => {
    if (dataPage.name !== val) {
      dataPage.name = val
      loading2.value = true
      brandPageSelect(dataPage).then((res) => {
        brandData.value = res.data.data.rows
        loading2.value = false
      })
    }
  }, 500)

  const remoteMethod2 = _.throttle((val) => {
    if (dataPage2.name !== val) {
      dataPage2.name = val
      loading3.value = true
      typePageSelect(dataPage2).then((res) => {
        typeData.value = res.data.data.rows
        loading3.value = false
      })
    }
  }, 500)
  // 分页改变时
  const getSizeList = () => {
    getList(false)
  }
  // 页码改变时
  const getNumList = () => {
    getList(false)
  }
  // 批量操作勾选
  const changeAll = (val) => {
    if (val) {
      activeId.value = val.map((o) => {
        return {
          id: o.id,
          tableType: o.tableType,
        }
      })
    }
  }
  // 批量操作
  const handleClick = (val) => {
    if (val == 1) {
      if (activeId.value.length == 0) {
        ElMessage({
          type: 'warning',
          message: '请先选择激活的商品！',
          duration: 4000,
        })
        return
      }
      ElMessageBox.confirm('确定激活选择的商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        autofocus: false,
      }).then(() => {
        activCode(activeId.value).then((res) => {
          if (res.data.code == 20000) {
            activeId.value = []
            getList(false)
          }
          if (res.data.isError)
            ElMessage({
              type: res.data.success ? 'success' : 'error',
              message: res.data.message,
              duration: 4000,
            })
        })
      })
    } else {
      if (!activeId.value) {
        ElMessage({
          type: 'warning',
          message: '请先选择删除的商品！',
          duration: 4000,
        })
        return
      }
      ElMessageBox.confirm('确定删除选择的商品吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        autofocus: false,
      }).then(() => {
        deleteCode(activeId.value).then((res) => {
          if (res.data.isError)
            ElMessage({
              type: res.data.success ? 'success' : 'error',
              message: res.data.message,
              duration: 4000,
            })
          if (res.data.code == 20000) {
            activeId.value = []
            getList(false)
          }
        })
      })
    }
  }

  watch(
    () => route.name,
    (value) => {
      if (value === 'Codelist') {
        getList(false)
      }
    },
  )
</script>

<style scoped lang="scss">
  @import './index';
</style>
